package mashibing.class4;

import util.MathUtil;

import java.util.Arrays;

/**
 * 在一个数组中，
 * 任何一个前面的数a，和任何一个后面的数b，
 * 如果(a,b)是降序的，就称为逆序对
 * 返回数组中所有的逆序对
 *
 * @author yujiafan
 * @version 1.0.0
 * @create 2023-03-21
 */
public class Class4_3_ReversePair {

    public static int reversePairNum(int[] arr) {
        if (arr == null || arr.length < 2) {
            return 0;
        }
        return process(arr, 0, arr.length - 1);
    }

    public static int process(int[] arr, int L, int R) {
        if (L == R) {
            return 0;
        }
        int M = L + ((R - L) >> 1);
        return process(arr, L, M)
                + process(arr, M + 1, R)
                + merge(arr, L, M, R);
    }

    public static int merge(int[] arr, int L, int M, int R) {
        int[] help = new int[R - L + 1];
        int p1 = M;
        int p2 = R;
        int index = R - L;
        int ans = 0;
        while (p1 >= L && p2 > M) {
            ans += arr[p1] > arr[p2] ? p2 - M : 0;
            help[index--] = arr[p1] > arr[p2] ? arr[p1--] : arr[p2--];
        }
        while (p1 >= L) {
            help[index--] = arr[p1--];
        }
        while (p2 > M) {
            help[index--] = arr[p2--];
        }
        for (int i = 0; i < help.length; i++) {
            arr[L + i] = help[i];
        }
        return ans;
    }

    public static int test(int[] arr) {
        if (arr == null || arr.length < 2) {
            return 0;
        }
        int ans = 0;
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                ans += arr[i] > arr[j] ? 1 : 0;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
//        int[] arr = {7, 6, 6, 2, 3}; // 4 + 2 + 2 + 0 + 0 = 8
//        System.out.println(reversePairNum(arr));

        int testCount = 50000;
        boolean flag = true;
        for (int i = 0; i < testCount; i++) {
            int[] arr1 = MathUtil.generateArray(100,100);
            int[] arr2 = MathUtil.copyArray(arr1);
            int ans1 = reversePairNum(arr1);
            int ans2 = test(arr2);
            if(ans1 != ans2){
                flag = false;
                System.out.println("error");
                System.out.println(Arrays.toString(arr1));
            }
        }
        if(flag){
            System.out.println("success");
        }
    }

}
